<?php
/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author LongLT
 */

class AnnouncementController extends ControllerBase
{
	public function init() {
		Util::app()->theme = ADMIN_THEME;
		parent::init();
		$this->registerFancybox();
	}

	public function registerFancybox(){
		Util::registerScriptFile(Util::themeUrl().'/js/jquery-ui-1.10.3.custom.min.js');
		Util::registerScriptFile(Util::themeUrl().'/js/custome.datepicker.js');
		// Add mousewheel plugin (this is optional)
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

		// Add fancyBox main JS and CSS files
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
		Util::registerCssFile(Util::themeUrl().'/js/fancybox/jquery.fancybox.css?v=2.0.6','screen');

		if (isset($_GET['ajax']))
			$this->layout = '//layouts/none';
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=>Util::getSuperMods(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		// Update db when event_end_date >= date()
		//Announcement::model()->updateAll(array('status' => 0)," CAST(event_end_date as DATE) < '".date("d/m/Y")."'");

		$model=new Announcement('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Announcement'])) {
			$model->attributes=$_GET['Announcement'];
		}
		elseif(isset($_POST['Announcement'])) {
			$model->attributes=$_POST['Announcement'];
		}

		/*
		 * Download excel
		 */
		if(isset($_POST['announcement_excel']) || isset($_POST['announcement_detail_excel'])) {
			$start	= isset($_POST["Statistic"]['start_year']) ? $_POST["Statistic"]['start_year'] : "";
			$end	= isset($_POST["Statistic"]['end_year']) ? $_POST["Statistic"]['end_year'] : "";
			$dataProvider 				= $model->search($start, $end)->getData();
			$announcement_id 			= array();
			$dataPrint['announcement']	= array();
			$dataPrint['assign']		= array();
			$dataPrint['views']			= array();
			$tplExcel					= "";
			$countData					= 0;

			// Get data
			foreach($dataProvider as $data) {
				$dataPrint["announcement"][] = $data->attributes;
				$announcement_id[] = $data->id;
			}

			if (!empty($announcement_id)) {
				// Statistic view, assign
				if(isset($_POST['announcement_excel'])) {
					$dataPrint["assign"] = AnnouncementAssign::model()->countByAnnouncement($announcement_id);
					//$dataPrint["views"] = AnnouncementView::model()->countByAnnouncement($announcement_id);
					$tplExcel = "announcementList001";
					$countData = count($dataPrint["announcement"]);
				}
				else {
					$dataPrint["assign"] = AnnouncementAssign::model()->assignAnnouncement($announcement_id);
					$tplExcel = "announcementList003";
					$countData = count($dataPrint["assign"]);
				}
			}

			// Print
			if ($countData > 0) {
				$objDownloadExcel = new DownloadExcel();
				$objDownloadExcel->CreateByListControl($tplExcel, $dataPrint, $countData);
			}
		}



		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		// Count assign
		$model = Announcement::model()->getAnnouncementAndCount($id);
		// Count views
		//$views = AnnouncementView::model()->with('announcement', 'member', 'member.memberCode')->countByAttributes(array('announcement_id' => $id));
		$this->render('view', array('model' => $model));
	}

	/**
	 * Creates a new model.
	 */
	public function actionCreate()
	{
		$model=new Announcement;
		// Set default value
		$model->status = 1;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Announcement']))
		{
			$model->attributes=$_POST['Announcement'];
			$model->created = date("Y-m-d H:i:s");
			//$model->event_end_date = date("Y-m-d H:i:s", strtotime($model->event_end_date));
			$model->user_id = Yii::app()->user->id;
			if($model->save()){
				$arrUrl = array('view','id'=>$model->id);
				if (isset($_GET['ajax'])) {
					$arrUrl['ajax'] = true;
				}
				$this->redirect($arrUrl);
			}
		}

		$this->render('create',compact('model'));
	}

	/**
	 * Updates a particular model.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Announcement']))
		{
			$model->attributes=$_POST['Announcement'];
			$model->updated = date("Y-m-d H:i:s");
			//$model->event_end_date = date("Y-m-d H:i:s", strtotime(str_replace('/', '-', $model->event_end_date)));

			if($model->save()){
				$arrUrl = array('view','id'=>$model->id);
				if (isset($_GET['ajax'])) {
					$arrUrl['ajax'] = true;
				}
				$this->redirect($arrUrl);
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$ids = $_POST['chk'];
			if (is_array($ids))
				foreach ($ids as $key)
					$rs = Announcement::model()->deleteByPk($key);
			if (isset($_GET['ajax'])) {
				echo CHtml::tag ('div', array('class' => 'flash-success'), "Term ID #{$key} has been deleted.");
				exit;
			} else {
				$this->setFlash("Thông báo [{$key}] đã được xóa.");
				$this->redirect(array('index'));
			}

		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Update_status
	 */
	public function actionUpdate_status($id, $returnUrl) {
		// Update for Announcement
		$model = $this->loadModel($id);
		$model->status = ($model->status == 1) ? 0 : 1;
		$model->update('status');

		// Update for AnnouncementAssign
		if ($model->status == 0) {
			AnnouncementAssign::model()->updateAll(array('event_joined' => 1),"announcement_id='".$id."' and purpose_join='1'");
		}

		if (!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array($returnUrl));
		exit;
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Announcement::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='announcement-form')
		{
			echo CActiveForm::validate($model);
			Util::app()->end();
		}
	}

	/**
	 * Display announcement with member
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionAssign($id)
	{
		$announcement = $this->loadModel($id);
		$model = new Member('search');

		// Default search
		$model->invite = 0;
		self::setCondMember($model, $id);

		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Member']))
			$model->attributes=$_GET['Member'];

		$this->render('assign',array(
			'model'=>$model,
			'announcement' => $announcement,
			'ajax'	=> isset($_GET["ajax"]) ? true : false
		));
	}

	/**
	 * Display announcement with member
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionViewAssign($id, $search = "")
	{
		$announcement = $this->loadModel($id);
		$model = new Member('search');

		// Default search
		$model->invite = 1;
		self::setCondMember($model, $id, $search);
		//$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Member']))
			$model->attributes=$_GET['Member'];

		// Statistic
		$dataProvider = $model->search();
		$statistic = self::statistic($dataProvider);
		//$statistic = Announcement::model()->getAnnouncementAndCount($id);

		$this->render('view_assign',array(
			'model'=>$model,
			'announcement' => $announcement,
			'statistic' => $statistic,
			'ajax'	=> isset($_GET["ajax"]) ? true : false
		));
	}

	/**
	 * Update_event_joined
	 */
	public function actionUpdate_event_joined($assign_id) {
		$model = AnnouncementAssign::model()->findByPk($assign_id);
		$model->event_joined = ($model->event_joined == 1) ? 0 : 1;
		$model->update('event_joined');
		echo 1;
		exit;
	}

	/**
	 * Deletes a particular model.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionInsert_assign()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$ids = $_POST['chk'];
			$announcement_id = $_POST['announcement_id'];
			if (is_array($ids)) {
				$condition = 'announcement_id = ' . $announcement_id;
				foreach ($ids as $member_id) {
					if (AnnouncementAssign::model()->exists($condition . ' AND member_id = ' . $member_id) == false) {
						// Insert new record
						$model=new AnnouncementAssign;
						$model->announcement_id = $announcement_id;
						$model->member_id = $member_id;
						$model->save();
					}
				}
			}
			if (isset($_GET['ajax'])) {
				echo CHtml::tag ('div', array('class' => 'flash-success'), "Term ID #{1} has been deleted.");
				exit;
			} else {
				$this->setFlash("Thông báo [{1}] đã được xóa.");
				$this->redirect(array('assign/id/' . $announcement_id));
			}

		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Deletes a particular model.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete_assign()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$ids = $_POST['chk'];
			$announcement_id = $_POST['announcement_id'];
			$announcement=$this->loadModel($announcement_id);

			if (is_array($ids) && is_array($announcement->attributes) && !empty($announcement->attributes)) {
				$condition = 'announcement_id = ' . $announcement_id;


				foreach ($ids as $member_id) {
					$record = AnnouncementAssign::model()->with(
									'member')->find(array(
									'select'=>'id, view_fg',
									'condition'=> $condition . ' AND member_id = ' . $member_id
								));

						if ($record !== null) {
						if ($announcement->event_fg == 1 && $record->view_fg == 1) {
							// Send mail
							$subject = "Hủy thư mời từ quản trị Khuyến Tài club.";
							$message = "Ban quản trị Khuyến Tài club đã hủy thư mời tham gia sự kiện \"" . $announcement->title . "\".<br>" .
										"Lý do hủy: " . $_POST['comment'] . ".<br>" .
										"Mọi thắc mắc vui lòng liên hệ với quản trị Khuyến Tài club thông qua địa chỉ mail " . Yii::app()->params['adminEmail'];

							//Util::sendMail('kimxuyen0610@gmail.com',$subject,$message);
							$send = Util::sendMail($record->member->email,Yii::app()->params['adminEmail'],$subject,$message);
						}
						$rs = AnnouncementAssign::model()->deleteByPk($record->id);
					}
				}
			}
			if (isset($_GET['ajax'])) {
				echo 1;
				exit;
			} else {
				$this->setFlash("Thông báo [{$key}] đã được xóa.");
				$this->redirect(array('index'));
			}

		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Display announcement with member
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionStatistic($id, $search = "")
	{
		if(Yii::app()->request->isPostRequest) {
			$model = new Member('search');

			// Default search
			//$model->unsetAttributes();  // clear any default values
			self::setCondMember($model, $id, $search);
			if(isset($_GET['Member'])) {
				$model->attributes=$_GET['Member'];
			}

			// Statistic
			$dataProvider = $model->search();
			$statistic = self::statistic($dataProvider);

			echo $statistic['count_view'] . "##" . $statistic['count_assign'] . "##" . $statistic['count_no_reply'] . "##"
				 . $statistic['count_purpose_join'] . "##" . $statistic['count_no_join'] . "##" . $statistic['count_joined'] . "##";

		}
	}

	/**
	 * Add condition for model Member
	 * @param integer $id the ID of the model to be updated
	 */
	public function setCondMember(&$model, $id, $search = "") {
		$model->announcement_id = $id;

		switch ($search) {
			case "view":
				$model->view_fg = 1;
				$model->invite = 1;
			break;
			case "invite":
				$model->invite = 1;
			break;
			case "purpose_0":
				$model->invite = 1;
				$model->purpose_join = 0;
			break;
			case "purpose_1":
				$model->invite = 1;
				$model->purpose_join = 1;
			break;
			case "purpose_2":
				$model->invite = 1;
				$model->purpose_join = 2;
			break;
			case "joined":
				$model->invite = 1;
				$model->event_joined = 1;
			break;
			default:
				//$model->invite = 1;
				//$model->scholarship = 1;
				//$model->course_name = date('Y');;
			break;
		}
	}

	/**
	 * Statistic announcement
	 * @param integer $id the ID of the model to be updated
	 */
	public function statistic($model) {
		$statistic = array( 'count_view' => 0,
							'count_assign' => 0,
							'count_no_reply' => 0,
							'count_purpose_join' => 0,
							'count_no_join' => 0,
							'count_joined' => 0,
		);
		foreach($model->getData() as $data) {

			/*if (isset($data->views) && $data->views->id != null) {
				$statistic['count_view']++;
			}*/
			if (isset($data->assigns) && $data->assigns->id != null) {
				$statistic['count_assign']++;
				if ($data->assigns->view_fg === "1") {
					$statistic['count_view']++;
				}
				if ($data->assigns->purpose_join === "0") {
					$statistic['count_no_reply']++;
				}
				if ($data->assigns->purpose_join == "1") {
					$statistic['count_no_join']++;
				}
				if ($data->assigns->purpose_join === "2") {
					$statistic['count_purpose_join']++;
				}
				if ($data->assigns->event_joined === "1") {
					$statistic['count_joined']++;
				}
			}
		}

		return $statistic;
	}
	/**
	 * actionDownloadExcel()
	 */
	public function actionDownloadExcel() {

		// Get variables
		$id		= isset($_POST['id']) ? $_POST['id'] : "";

		if ($id != "") {
			$announcement = $this->loadModel($id);
			$dataPrint['announcement']	= $announcement->attributes;
			$dataPrint['assign']		= array();
			$countData					= "";

			// Get data
			$dataPrint["assign"] = AnnouncementAssign::model()->assignAnnouncement($id);

			// Print
			$objDownloadExcel = new DownloadExcel();
			$objDownloadExcel->CreateByListControl("announcementList002", $dataPrint, count($dataPrint["assign"]));
		}
    }
}
